﻿using HBase.db;
using hCommand;
using System;
using System.Collections.Generic;
using System.Data;

namespace Persistence {
    public class CsdOutEngine : GkTransaction {
        public long id;
        public bool deleteStock = false;
 
        protected override TransRes Execute() {

            CoreStockDet csd = getById<CoreStockDet>(id);
            if (csd == null) {
                return new TransRes("明细不存在" + id);
            }
           
            if (csd.dooDetId > 0) {
                WhDooDet det = getById<WhDooDet>(csd.dooDetId);
                if (det != null) {
                    var res= updataStatus(csd, StockDetailStatus.单据手动出库); 
                    return res;
                } 
                WhDopk pk = getById<WhDopk>(csd.dooDetId);
                if (pk == null) {
                    return new TransRes("出库单据异常");
                } else {
                    return new TransRes("盘库中");//StockDetailStatus.单据盘亏出库
                }  
            }else  if (csd.status == (int)StockDetailStatus.编辑) {
                return updataStatus( csd,StockDetailStatus.直接编辑出库 ); 
            } else if (csd.status == (int)StockDetailStatus.待绑定) {
                return updataStatus(csd, StockDetailStatus.直接库外出库); 
            } else if (csd.status == (int)StockDetailStatus.库存) {
                return updataStatus(csd, StockDetailStatus.直接库存出库); 
            }

       
            return new TransRes(); 
        }

        TransRes updataStatus(CoreStockDet csd, StockDetailStatus s) {
            String sql = "update core_stock_det set out_time=sgj_get_sys_now , status=@status where id=@id";
            exec(sql, new { csd.id, status = (int)s });
           
            exec("update Core_Stock set  change_Time=sgj_get_sys_now where id=@id", new { id = csd.pid });
            StatUtil.changeBatch(this,  csd ,false); 
            if (deleteStock) {
                String checkSql = "select count(*) from core_stock_det  where  status>=0 and pid =@pid   ";
                int res = queryUnique<int>(checkSql, csd);
                if (res == 0) {
                    string sql2 = @"UPDATE  core_stock SET status =@status WHERE id=@stockId";
                    exec(sql2, new { stockId = csd.pid, status = (int)StockStatus.明细出库同步删除 });
                }
            }
            exec("update Wh_Doo_Det set cv=cv+1 where id=@dooDetId", csd);
            return new TransRes(true,s.ToString());
        }
    }
}
